var Login = function () {

    //workaround for 408
    setInterval(function () {
        window.location.reload();
    }, 1200000);
	
	$.validator.addMethod('mobile', function( value, element ) {
		return this.optional( element ) || /^1[34578]\d{9}$/.test( value );
	}, "请输入有效的手机号码");

    $.validator.addMethod('loginName', function( value, element ) {
        return this.optional( element ) || /^[a-zA-Z]{1}([a-zA-Z0-9]|[_]){1,30}$/.test( value );
    }, "用户名必须以字母开头，可以包括数字和下划线");

    $.validator.addMethod('password1', function( value, element ) {
        return this.optional( element ) || /^(\w)[a-zA-Z0-9]|[_]$/.test( value );
    }, "密码只能包括字母、数字和下划线");

    var onError = function(errorCode) {
        $('#succModal .modal-header').css("backgroundColor","red");
        $('#succModal h4').html("操作失败");
        var errorMsg = "我们抱歉的通知您！目前服务不可用，请稍后重试！";
        if (errorCode=="COMPANY_ACCOUNT_NOT_ACTIVE") {
            errorMsg = "我们抱歉的通知您：您所在公司的公司帐号未处于启用状态（到期或停用等），请联系贵公司系统管理人员以获取帮助！";
        } else if (errorCode=="MAX_ACTIVE_ACCOUNT_EXCEED") {
            errorMsg = "我们抱歉的通知您：您所在公司的活动注册帐号已达到额定值，请联系贵公司系统管理人员以获取帮助（可能需要升级公司帐号）！";
        }
        $('#succModal .modal-body').html(errorMsg);
        $('#succModal').modal({keyboard:true});
    }

    var onErrorForget = function(errorCode) {
        $('#succModal .modal-header').css("backgroundColor","red");
        $('#succModal h4').html("操作失败");
        var errorMsg = "我们抱歉的通知您！目前服务不可用，请稍后重试！";
        if (errorCode=="NOT_AN_ACCOUNT") {
            errorMsg = "我们抱歉的通知您：您输入的帐号状态异常，请联系客服人员以获取帮助！";
        } else if (errorCode=="NOT_ACTIVATED_ACCOUNT") {
            errorMsg = "我们抱歉的通知您：您所操作的帐号尚未激活，请先激活再进行其他操作！";
        }
        $('#succModal .modal-body').html(errorMsg);
        $('#succModal').modal({keyboard:true});
    }

	var handleLogin = function() {
		$('.login-form').validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: ".ignore",
            rules: {
                j_username: {
                    required: true,
                    maxlength: 20
                },
                j_password: {
                    required: true,
                    maxlength: 20
                },
                captcha: {
                    minlength: 4,
                    maxlength: 4,
                    required: true
                },
                remember: {
                    required: false
                }
            },

            messages: {
                j_username: {
                    required: "请输入登录名，邮箱或手机号"
                },
                j_password: {
                    required: "请输入密码"
                },
                captcha: {
                    required: "请输入验证码"
                }
            },

            invalidHandler: function (event, validator) { //display error alert on form submit

            },

            highlight: function (element) { // hightlight error inputs
                $(element).closest('.form-group').addClass('has-error');
            },

            success: function (label) {
                $('.alert-danger', $('.login-form')).hide();
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },

            errorPlacement: function (error, element) {
                error.insertAfter(element.closest('.input-icon'));
            },

            submitHandler: function (form) {
                form.submit();
            }

        });

        if (window.location.search=='?loginfail') {
            $('.alert-danger', $('.login-form')).show();
        }

        $('.login-form input').keypress(function (e) {
            if (e.which == 13) {
                loginForm = $(".login .login-form");
                doSumit(loginForm);
                return false;
            }
        });

        //bind captcha
        $('.login-form .img-captcha').attr('src', api_loc+'/auth/captcha');
        $('.login-form .btn-refresh-captcha').click(function () {
            $('.login-form .img-captcha').attr('src', api_loc+'/auth/captcha?'+new Date().getTime());
        });

        var loginForm = $(".login .login-form");
        if (loginForm.attr('action')=='/') {
            $('.login .alert-danger').find('span').html('');
            //loginForm.attr('action', api_loc+'/auth/login');return;
            $('.login-form .submitbtn').click(function (e) {
                doSumit(loginForm);
            });
        } else {
            $('.login-form .submitbtn').click(function (e) {
                if ($('.login-form').validate().form()) {
                    $('.login-form').submit();
                }
            });
        }

	}

    function doSumit(loginForm) {
        if (loginForm.validate().form()) {
            $.ajax({
                url: api_loc+'/auth/login?'+new Date().getTime(),
                cache: false,
                method: 'post',
                dataType: 'json',
                data: {
                    j_username: loginForm.find('input[name="j_username"]').val(),
                    j_password: loginForm.find('input[name="j_password"]').val(),
                    time: new Date().getTime(),
                    captcha: loginForm.find('input[name="captcha"]').val()
                },
                success: function (ret) {
                    if (!ret) {
                        window.location.reload();
                    } else {
                        if (ret.result==0) {
                            if (ret.msg=='WRONG_CAPTCHA') {
                                $('.login .alert-danger').show().find('span').html('验证码错误');
                            } else if (ret.msg=='WRONG_PWD' || ret.msg=='NO_USER') {
                                $('.login .alert-danger').show().find('span').html('用户名或密码错误');
                            }
                        } else {
                            //login success
                            $('.login .alert-danger').hide();
                            window.location.href=loginForm.attr('success-url');
                        }
                    }
                }
            });
        }
    }

	var handleForgetPassword = function () {

    	function submitForgetForm() {
            if ($(".forget-form").validate().form()) {
                $(".forget-form").ajaxSubmit({
                    type: 'post',
                    url: '/bpmp-engine/openapi/v1/user/resetPwd',
                    data: {
                    	email : $.trim($(".forget-form input[name='email']").val())
                    },
                    success: function (data) {
                        if (data && data.result) {
                            $('#succModal .modal-header').css("backgroundColor","#2c8bfb");
                            $('#succModal').modal();
                            $('#succModal .modal-body').html('您的密码重置申请已处理成功，请访问您的邮箱查看详细信息！');
                            $(".forget-form input[name='email']").val('')
                            $("#forget-back-btn").trigger("click");
                        } else {
                            onErrorForget(data.errorCode);
                        }
                    },
                    error : onErrorForget
                });
            }
		}

		$('.forget-form').validate({
			errorElement: 'span',
			errorClass: 'help-block',
			focusInvalid: false,
            onkeyup: false,
			ignore: "",
			rules: {
				email: {
					required: true,
					email: true,
					remote : {
						url: "/bpmp-engine/openapi/v1/user/checkAttr",
						data : {"reverse" : "true"},
						type: "GET"
					},
					maxlength: 40
				}
			},

			messages: {
				email: {
					required: "请输入邮箱",
					remote: "注册邮箱地址不存在，请核实后再试"
				}
			},

			highlight: function (element) { // hightlight error inputs
				$(element).closest('.form-group').addClass('has-error');
			},

			success: function (label) {
				label.closest('.form-group').removeClass('has-error');
				label.remove();
			},

			errorPlacement: function (error, element) {
				error.insertAfter(element.closest('.input-icon'));
			},

		});

        $('#forget-submit-btn').click(function (e) {
            submitForgetForm();
        });

		$('.forget-form input').keypress(function (e) {
			if (e.which == 13) {
				submitForgetForm();
			}
		});

		jQuery('#forget-password').click(function () {
			jQuery('.login-form').hide();
			jQuery('.forget-form').show();
		});

		jQuery('#forget-back-btn').click(function () {
			jQuery('.login-form').show();
			jQuery('.forget-form').hide();
		});

	}

	var handleRegister = function () {

		/*function format(state) {
            if (!state.id) return state.text; // optgroup
            return "<img class='flag' src='../../assets/global/img/flags/" + state.id.toLowerCase() + ".png'/>&nbsp;&nbsp;" + state.text;
        }

		$("#select2_sample4").select2({
		  	placeholder: '<i class="fa fa-map-marker"></i>&nbsp;选择国家',
            allowClear: true,
            formatResult: format,
            formatSelection: format,
            escapeMarkup: function (m) {
                return m;
            }
        });*/


		$('#select2_sample4').change(function () {
			$('.register-form').validate().element($(this));
		});


         $('.register-form').validate({
			errorElement: 'span',
			errorClass: 'help-block',
			focusInvalid: false,
            onkeyup: false,
			ignore: "",
			rules: {
				inviteCode: {
					required: true,
					remote : {
						url: "/bpmp-engine/openapi/v1/tenant/checkInviteCode",     //后台处理程序
						type: "GET"
					}
				},
				loginName: {
					required: true,
					loginName: true,
					remote : {
						url: "/bpmp-engine/openapi/v1/user/checkAttr",     //后台处理程序
						type: "GET"
					},
					maxlength: 20,
					minlength: 3
				},
				password: {
					required: true,
					password1: true,
					maxlength: 20,
					minlength: 6
				},
				rpassword: {
					password1: true,
					equalTo: "#register_password"
				},
				email: {
					required: true,
					email: true,
					remote : {
						url: "/bpmp-engine/openapi/v1/user/checkAttr",
						type: "GET"
					},
					maxlength: 40
				},
				mobile: {
					required: true,
					remote : {
						url: "/bpmp-engine/openapi/v1/user/checkAttr",
						type: "GET"
					},
					mobile: true
				},
				realName: {
					required: true,
					maxlength: 20,
					minlength: 2
				},
                /*address: {
					required: true,
					maxlength: 40
				},
				city: {
					required: true,
					maxlength: 20
				},
				country: {
					required: true,
					maxlength: 20
				},*/
				tnc: {
					required: true
				}
			},

			messages: { // custom messages for radio buttons and checkboxes
				inviteCode : {
					remote : "邀请码不存在，请确保企业号已注册并联系企业号注册人"
				},
				loginName : {
					remote : "该用户名已被占用"
				},
				email : {
					remote : "该邮箱地址已被注册"
				},
				mobile : {
					remote : "该手机号已被注册"
				},
				tnc: {
					required: "请先接受条款"
				}
			},

			invalidHandler: function (event, validator) { //display error alert on form submit

			},

			highlight: function (element) { // hightlight error inputs
				$(element)
					.closest('.form-group').addClass('has-error'); // set error class to the control group
			},

			success: function (label) {
				label.closest('.form-group').removeClass('has-error');
				label.remove();
			},

			errorPlacement: function (error, element) {
				if (element.attr("name") == "tnc") { // insert checkbox errors after the container
					error.insertAfter($('#register_tnc_error'));
				} else if (element.closest('.input-icon').size() === 1) {
					error.insertAfter(element.closest('.input-icon'));
				} else {
					error.insertAfter(element);
				}
			}
		});

		/*$('.register-form input').keypress(function (e) {
			if (e.which == 13) {
				if ($('.register-form').validate().form()) {
					$('.register-form').submit();
				}
				return false;
			}
		});*/

		$("#register-submit-btn").click(function() {
			if ($(".register-form").validate().form()) {
				$(".register-form").ajaxSubmit({
					type: 'post',
					url: '/bpmp-engine/openapi/v1/user/register',
					data: {
					},
					success: function (data) {
						if (data && data.result) {
                            $('#succModal .modal-header').css("backgroundColor","#2c8bfb");
							$('#succModal').modal();
                            $('#succModal .modal-body').html('感谢您的注册！请访问您的邮箱接收确认邮件以激活您的帐号！');
                            $("#register-back-btn").trigger("click");
						} else {
							onError(data.errorCode);
						}
					},
					error : onError
				});
			}
		});

		jQuery('#register-btn').click(function () {
			jQuery('.login-form').hide();
			jQuery('.register-form').show();
		});

		jQuery('#register-back-btn').click(function () {
			jQuery('.login-form').show();
			jQuery('.register-form').hide();
		});
	}
    
    return {
        //main function to initiate the module
        init: function () {
        	
            handleLogin();
            handleForgetPassword();
            handleRegister();

            $('input[name="j_username"]').focus();
        }

    };

}();